import {Component, Input, OnInit, TemplateRef, ViewChildren} from '@angular/core';
import {LocalDataSource, ViewCell} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {NbDialogService} from "@nebular/theme";
import {ActivatedRoute, Router} from "@angular/router";
import {DisableEditRender} from "../../utils/DisableEditRender";
import {AdminService} from "../../AdminService";
import {DocService} from "../../energy/api";
import {UnitInfo} from "../../energy/api/model/unitInfo";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {ResponseUnitInfo} from "../../energy/api/model/responseUnitInfo";
import {UnitDetailComponent} from "./unit-detail.component";
import {CustomMoneyRender} from "../../utils/CustomMoneyRender";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './unit-document.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }

    button {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 10px;
    }

    .margin {
      margin: 10px;
    }
  `],
})
export class UnitDocumentComponent implements OnInit {
  settings = {
    pager: {
      display: true,
      perPage: 10
    },
    hideSubHeader: true,
    actions: {
      columnTitle: '操作',
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      unitNo: {
        title: '单元编号',
        type: 'custom',
        renderComponent: CustomUnitLinkRender
      },
      unitName: {
        title: '单元名称',
        type: 'string',
      },
      address: {
        title: '地址',
        type: 'string',
      },
      netArea: {
        title: '面积',
        type: 'string',
      },
      contract: {
        title: '联系人',
        type: 'string',
      },
      contractTel: {
        title: '联系电话',
        type: 'string',
      },
      buildingId: {
        title: '楼栋ID',
        type: 'number',
      },
      floorNo: {
        title: '楼层编号',
        type: 'string',
      },
      balance: {
        title: '余额',
        type: 'custom',
        renderComponent:CustomMoneyRender
      },
      limit:{
        title: '限额',
        type: 'custom',
        renderComponent: CustomMoneyRender
      },
      extInfo: {
        title: '备注',
        type: 'string',
      },
      user: {
        title: '客户列表',
        type: 'html',
        editable: false,
        editor: {
          type: 'custom',
          component: DisableEditRender,
        }
      },
      device: {
        title: '设备列表',
        type: 'html',
        editable: false,
        editor: {
          type: 'custom',
          component: DisableEditRender,
        }
      }
    },
  };
  source: DataDataSource;
  maxPage: number = 1;
  page: number = 1;
  limit: number = 25;
  bd?: number = null;
  unitNo: string = '';
  unitName: string = '';

  @ViewChildren('inputs') vc;

  constructor(private service: SmartTableData
              , private api: DocService
              , private route: ActivatedRoute
              , private dialogService: NbDialogService
              , private admin:AdminService) {

  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(value=>{
      const bd = value.get("bd");
      if (bd != null) this.bd = Number(bd);
      this.source  = new DataDataSource(this.api,this.bd);
    });
  }

  filter(){
    this.source.unitName = this.unitName;
    this.source.unitNo = this.unitNo;
    this.source.setPage(1);
    this.source.refresh();
  }


  openAddPrompt(dialog: TemplateRef<any>) {
    const keys = Object.keys(this.settings.columns).filter(k => {
      return (this.settings.columns[k]['type'] == 'string' || this.settings.columns[k]['type'] == 'number' || k=='limit')
    });
    const columns = keys.map(k => {
      return this.settings.columns[k];
    });
    this.dialogService.open(dialog, {
      context: columns
    }).onClose.subscribe(bool => {
      if (!bool) return;
      const data = <UnitInfo>{};
      const results = this.vc.map(v => v.nativeElement.value);
      keys.forEach((k, i) => {
        if (columns[i]['type'] == 'number') {
          data[k] = Number(results[i]);
        } else {
          data[k] = results[i];
        }

      });
      data['operateType'] = "0";
      this.api.postECASyncUnitInfo(new BaseRequest([data])).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    });
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECASyncUnitInfo(new BaseRequest(
        [{
          operateType: "2",
          unitId: event.data['unitId'],
        }]
      )).toPromise().then(res => {
        if (res.success) {
          event.confirm.resolve();
        } else {
          event.confirm.reject();
        }
      }).catch(e => {
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event): void {
    const newData = event.newData;
    newData['operateType'] = "1";
    delete newData['user'];
    delete newData['bindUser'];
    delete newData['device'];
    this.api.postECASyncUnitInfo(new BaseRequest([newData])).toPromise().then(response => {
      console.log(response);
      event.confirm.resolve();
    }).catch(e => {
      console.log(e);
      event.confirm.reject();
    })
  }
}

export class DataDataSource extends LocalDataSource {
  unitName:string = '';
  unitNo:string = '';
  all: number = -1;
  constructor(private api: DocService,private buildingId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      buildingId:this.buildingId
    };
    if(this.unitNo!='') query['unitNo'] = this.unitNo;
    if(this.unitName!='') query['unitName'] = this.unitName;
    return this.api.requestECAUnitInfo(new BaseRequest(query)).pipe(map((res:ResponseUnitInfo)=>{
      this.all = res.dataCount;
      return res.data.map(value=>{
        value['user'] = `<a href="/#/pages/doc/urd/${value.unitId}">查看客户</a>`;
        value['device'] = `<a href="/#/pages/doc/dl/${value.unitId}">查看设备</a>`;
        return value;
      });
    })).toPromise();
  }
}


@Component({
  template: `
    <a href="javascript:void(0);" (click)="jump()">{{renderValue}}</a>
  `,
})
export class CustomUnitLinkRender implements ViewCell, OnInit {

  renderValue: string;

  @Input() value: string | number;
  @Input() rowData: any;
  constructor(private router:Router){

  }
  ngOnInit() {
    this.renderValue = this.value.toString();
  }

  jump(){
    UnitDetailComponent.unit = this.rowData;
    this.router.navigateByUrl("/pages/doc/ud/ud");
  }

}
